package cn.yi.fast.mq.rocketmq.factorybean;

import cn.yi.fast.mq.rocketmq.message.handler.MessageHandler;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class Topic2MessageHandlerFactoryBean implements FactoryBean<Map<String,Map<String,MessageHandler>>>,InitializingBean {

    @Value("${mq.businessTopic}")
    private String topic;

    @Autowired
    private List<MessageHandler> messageHandlers;

    private Map<String, Map<String, MessageHandler>> topic2TagHandler;


    @Override
    public Map<String, Map<String, MessageHandler>> getObject() throws Exception {
        return topic2TagHandler;
    }

    @Override
    public Class<?> getObjectType() {
        return Map.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        topic2TagHandler = new HashMap<>();
        Map<String, MessageHandler> tagHandler = new HashMap<>();
        if(!CollectionUtils.isEmpty(messageHandlers)){
            messageHandlers.forEach(b ->{
                Component c = b.getClass().getAnnotation(Component.class);
                if(Objects.nonNull(c)){
                    tagHandler.put(c.value(),b);
                }
            });
        }
        topic2TagHandler.put(topic,tagHandler);
    }
}
